/*
 * @Author: 码上talk|RC
 * @Date: 2021-05-03 22:30:33
 * @LastEditTime: 2021-09-28 16:33:51
 * @LastEditors: 码上talk|RC
 * @Description:
 * @FilePath: /tacomall-web/src/model/request.js
 * @微信:  13680065830
 * @邮箱:  3189482282@qq.com
 * @oops: Just do what I think it is right
 */
import apiJson from '@/config/api';
import { httpLib } from '@/lib/http';

export class Request {

  _loopTimer = null;

  _getRequestBaseUrl (url) {
    let finalBaseUrl = url.dev;

    if (process.env.NODE_ENV === 'local') {
      finalBaseUrl = url.lcoal;
    }

    if (process.env.NODE_ENV === 'test') {
      finalBaseUrl = url.test;
    }

    if (process.env.NODE_ENV === 'production') {
      finalBaseUrl = url.prod;
    }

    return finalBaseUrl;
  }

  _getConfig (app, domain, method) {
    return {
      fullUrl: this._getRequestBaseUrl(apiJson[app].url) + apiJson[app].domain[domain][method].path
    };
  }

  do (app, domain, method, form) {
    const { params, data } = form;
    let url = ''
    try {
      url = apiJson[app].domain[domain][method].path;
    } catch (e) {
      $log4js.error(`
      Request.js =====> api json configure is error
      full path ======> ${app}/${domain}/${method}
      `);
    }
    return httpLib.request({
      baseURL: this._getRequestBaseUrl(apiJson[app].url),
      url,
      params,
      data
    });
  }

  loopForOk (app, domain, method, form) {
    const { params, data } = form;
    const reqOptions = {
      baseURL: this._getRequestBaseUrl(apiJson[app].url),
      url: apiJson[app].domain[domain][method].path,
      params,
      data
    }
    return new Promise((resolve) => {
      this._loopTimer = setInterval(() => {
        httpLib.request(reqOptions).then(res => {
          const { status, data } = res;
          if (status) {
            clearInterval(this._loopTimer);
            this._loopTimer = null;
            resolve(data);
          }
        })
      }, 1500);
    });
  }

  clearLoop () {
    this._loopTimer && clearInterval(this._loopTimer);
    this._loopTimer = null;
  }
}
